import Snake from './Snake';
import Food from './Food';
import ScorePanel from './ScorePanel';

// 控制类
class  GameControl{

    snake:Snake;
    food:Food;
    scorePanel:ScorePanel;
       //移动方向
    direction :string='';
    //是否结束
    isLive=true;

   //构造器
    constructor(){
        this.snake = new Snake()
        this.food = new Food()
        this.scorePanel = new ScorePanel(10,3)
        this.direction = this.direction
        this.init()
    }



    //开始游戏
    init(){
        //绑定键盘
        document.addEventListener("keydown" ,this.keydownHandler.bind(this));
        //蛇移动
        this.run()
    }

    //键盘按下 /*  ArrowUp   ArrowRight  ArrowLeft   ArrowDown */
    keydownHandler(event:KeyboardEvent){
        this.direction = event.key
    }


    // 控制移动
    run(){
        let X = this.snake.X;
        let Y = this.snake.Y;

        //根据方向修改xy
        switch (this.direction) {
            case "ArrowUp":
            case "Up":
                Y-=10;
                break;
            case "ArrowRight":
            case "Right":
                X+=10;
                break;
            case "ArrowLeft":
            case "Left":
                X-=10
                break;
            case "ArrowDown":
            case "Down":
                Y+=10
                break;
        }

        // 检查是否吃到食物
        this.checkEat(X,Y);



        try {
            //修改xy
        this.snake.X=X
        this.snake.Y=Y
        } catch (error) {
            alert(error.message + "GAME OVER")
            this.isLive=false
        }




        //定时
        this.isLive && setTimeout(this.run.bind(this),300-(this.scorePanel.leve-1)*22)
    }


    // 检查是否吃到食物
    checkEat(X:number,Y:number){
        if(X==this.food.X&& Y==this.food.Y){
            this.food.change()
            this.scorePanel.addScore()
            this.snake.addBody()
        }
    }

}

export default GameControl
